const Admin = require("../models/Admin")
const md5 = require('md5');
exports.addAdmin = async function(adminObj){
    //新建用户的时候需要传递进去加密的密码
    const loginPwd = md5(adminObj.loginPwd);
    adminObj.loginPwd = loginPwd;
    const ins = await Admin.create(adminObj);
    const result = JSON.parse(JSON.stringify(ins))
    delete result.loginPwd
    return result
}

exports.delAdmin = async function(id){
    // 传入需要删除的id
   const ins =  await Admin.destroy({
        where:{
            id
        }
    })
    return ins;
}

exports.updateAdmin = async function (id,updateObj){
    // 如果修改密码login
    if(updateObj.loginPwd){
        // 如果更新的内容包括密码的话 需要将提交的这个密码重新加密
        const loginPwd = md5(updateObj.loginPwd);
        updateObj.loginPwd = loginPwd
    } 
    const ins = await Admin.update(updateObj,{
        where:{
            id
        }
    })
    return ins;
}

// 登录 一次查询一个用户
exports.login = async function(loginId,loginPwd){
    const result =await  Admin.findOne({
        where:{
            loginId,
            loginPwd
        }
    })
    return result.toJSON()
    // return result.toJSON();
}
// 使用md5处理密码

exports.loginStrict = async function(loginId,loginPwd){
    const pwd = md5(loginPwd) ;
    const result = await Admin.findOne({
        where:{
            loginId,
            loginPwd:pwd
        }
    })
    const target = JSON.parse(JSON.stringify(result))
    if(target && target.loginId===loginId ){
        delete target.loginPwd
        return target
    }else{
        return '账号或者密码出错'
    }
}

exports.findById = async function(id){
   const resp =  await Admin.findByPk(id);
   if(resp===null){
    console.log('没查到')
   }else{
    const returnData = JSON.parse(JSON.stringify(resp))
    delete returnData.loginPwd
    return returnData
   }

}

exports.getAllAdmin = async function(){
    const resp = await Admin.findAll({
        // 剔除用户密码等字段
        attributes:["id","loginId","name","createdAt"]
    })
    if(resp){
        return JSON.parse(JSON.stringify(resp))
    }
}